<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="diy-mb-5">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['admin:road:create']">新增</el-button>
    </div>

    <el-table v-loading="loading" :data="spparkplaceList" >
      <el-table-column
      v-for="(item,index) in tableList"
      :key="index"
      :label="item.label" align="center" :prop="item.prop" :width="item.width ? item.width : ''">
        <template
        slot-scope="{row}">
          <div v-if="item.prop == 'dataStatus'" v-hasPermi="['admin:appUser:updateStatus']">
            <el-switch
              v-model="row.dataStatus"
              :active-value="1"
              :inactive-value="2"
              @change="handleStatusChange(row)"
            ></el-switch>
          </div>
          <div v-else>{{row[item.prop]}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handleUpdate(row)"
            v-hasPermi="['admin:appUser:update','admin:appUser:get']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handSetPark(row)"
            v-hasPermi="['admin:appUser:setPark']"
          >设置停车场
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handSetMenu(row)"
            v-hasPermi="['admin:appUser:setMenu']"
          >设置菜单
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-unlock"
            @click="handlePassword(row)"
            v-hasPermi="['admin:appUser:updatePassWord']"
          >修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改PP用户信息对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px">
        <el-row v-if="title == '设置菜单'">
          <el-col :span="24">
            <el-form-item label="菜单" prop="menuIds">
              <el-select
                style="width: 100%;"
                v-model="form.menuIds"
                placeholder="请选择菜单"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="item in menuList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else-if="title == '设置停车场'">
          <el-col :span="24">
            <el-form-item label="停车场" prop="parkIds">
              <div id="tree">
                <el-tree
                  ref="dept"
                  :data="jigouList"
                  :load="loadNode"
                  lazy
                  @check-change="handleCheckChange"
                  :default-checked-keys="form.parkIds"
                  :props="parkDefaultProps"
                  :check-strictly="true"
                  empty-text="加载中，请稍候"
                  class="tree-border"
                  show-checkbox
                  node-key="id"/>
              </div>
              <!-- <el-select
                style="width: 100%;"
                v-model="form.parkIds"
                placeholder="请选择菜单"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="item in parkList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-else>
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!form.id">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入登录密码" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog :title="title" :visible.sync="openPwd" width="600px" append-to-body>
      <el-form ref="form_pwd" :model="form_pwd" :rules="rules_pwd" label-width="116px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="密码" prop="newPassword">
              <el-input v-model="form_pwd.newPassword" placeholder="请输入密码" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwd">确 定</el-button>
        <el-button @click="openPwd = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, appUserDetail, appUserAdd, appUserUpdate,
updateStatus,updatePassWord,setPark,setMenu,listPark,listMenu,listAppMenu} from "@/api/app/appUser";
import { getListAuthPark,getDepartmentList } from '@/api/base'
const sm3 = require('miniprogram-sm-crypto').sm3;
import { validateMobile } from '@/utils/validate'
export default {
  name: "appUser",
  dicts: ['EYesOrNo',],
  components:{},
  data() {
    return {
      parkDefaultProps: {
        children: 'parkList',
        label: 'name',
        isLeaf: 'leaf',
        disabled: (data, node) => {
          if (node.level == 1) {
            return true
          } else {
            return false
          }
        }
      },
      tableList:[
        {label:'名称',prop:'name',},
        {label:'电话号码',prop:'phoneNumber',},
        {label:'状态',prop:'dataStatus',},
      ],//表格字段显示
      //片区数据
      areaList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车位信息表格数据
      spparkplaceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openPwd:false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      form_pwd:{},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        phoneNumber: [
          {required: true, message: "手机号不能为空", trigger: "change"},
          { validator: validateMobile.bind(this), trigger: 'blur' },
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"}
        ],
      },
      rules_pwd:{
        newPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      menuList:[],//菜单数据
      parkList:[],//停车长数据
      jigouList:[],//机构数据
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 所有停车节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的停车节点
      const checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的停车节点
      const halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    handleCheckChange(data, checked, indeterminate){//停车长改变
      console.log(data, checked, indeterminate);
      let id = data.id
      if(checked) {
        this.form.parkIds.push(data.id)
      }else{
        let index = this.form.parkIds.findIndex(item=>item == data.id)
        if(index != -1) this.form.parkIds.splice(index,1)
      }
      
    },
    async handSetPark(row){//设置停车场弹窗
      let form = {
        id:row.id
      };

      this.open = true;
      this.title = "设置停车场";
      let data = await this.listPark(row.id)
      let list = []
      data.map(item=>{
        list = list.concat(item.parkList)
      })
      list = list.map(item=>item.id)
      // list.forEach((v) => {
      //   this.$nextTick(() => {
      //     this.$refs.dept.setChecked(v, true, false)
      //   })
      // })
      console.log('list',list)
      form.parkIds = list
      this.form  = {...form}
      console.log('this.form',this.form)
      this.getDepartmentList()
    },
    async listPark(id){//APP用户菜单列表
      let res = await listPark(id)
      let data = res.data || []
      return data
    },
    async getDepartmentList(){//获取停车场
      let res = await getDepartmentList()
      let data = res.data || []
      this.jigouList = data.map(item => {
        return {
          ...item,
          disabled: true
        }
      })
    },
    async loadNode(node, resolve){//加载停车场
      console.log('node, resolve',node, resolve)
      if (node.level === 0) {
        return resolve([{ name: 'region' }]);
      }
      if (node.level > 1) return resolve([]);
      let obj = node.data || {}
      console.log(obj.id)
      let data = await this.getListAuthPark(obj.id)

      // setTimeout(() => {
      //   const data = [{
      //     name: 'leaf',
      //     leaf: true
      //   }, {
      //     name: 'zone'
      //   }];

      //   resolve(data);
      // }, 500);
      resolve(data);
      // this.form.parkIds.forEach((v) => {
      //   this.$nextTick(() => {
      //     console.log(v.id)
      //     this.$refs.dept.setChecked(v.id, true, false)
      //   })
      // })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({parkType:2,departmentId})
      let data = res.data || []
      this.parkList = data.map(item=>{
        return {
          ...item,
          leaf: true
        }
      })
      return this.parkList
    },
    async handSetMenu(row){//设置菜单弹窗
      let form = {
        id:row.id
      };

      this.open = true;
      this.title = "设置菜单";
      let data = await this.listMenu(row.id)
      form.menuIds = data
      this.form  = {...form}
      console.log('this.form',this.form)
      this.listAppMenu()
    },
    //修改密码
    handlePassword(row) {
      this.form_pwd = {id:row.id};
      this.openPwd = true;
      this.title = "修改密码";

    },
    async listMenu(id){//APP用户菜单列表
      let res = await listMenu(id)
      let data = res.data || []
      return data
    },
    async listAppMenu(){//获取全部菜单
      let res = await listAppMenu()
      let data = res.data || []
      this.menuList = data
    },
    createSm3Sign(key){//加密
    	return sm3(key)
    },
    //修改状态
    handleStatusChange(row) {
      console.log(row)
      this.$modal.confirm(`是否确认更新该数据项状态？`).then(function() {
        return updateStatus({
          id:row.id,
          dataStatus:row.dataStatus
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('操作成功');
      }).catch(() => {row.dataStatus = row.dataStatus ==1 ? 2 : 1 });
    },
    /** 查询车位信息列表 */
    getList() {
      this.loading = true;
      fetchList(this.queryParams).then(response => {
        let data = response.data || {}
        let rows = data.list || []
        this.spparkplaceList = rows.map(item=>{
          let parkNameList = item.parkNameList || []
          return {
            ...item,
            parkNameStr:parkNameList.toString()
          }
        });
        this.total = data.total || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.open = true;
      this.title = "添加APP用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pkParkplaceId = row.id
      appUserDetail(pkParkplaceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改APP用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if(this.title == '设置菜单'){
            // if(!form.menuIds.length) return this.$modal.msgWarning("请选择至少一个菜单");
            setMenu(form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }else if(this.title == '设置停车场'){
            // form.parkIds = this.getDeptAllCheckedKeys()
            delete form.parkId
            if(!form.parkIds.length) return this.$modal.msgWarning("请选择至少一个停车场");
            setPark(form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }else{
            if (this.form.id != null) {
              appUserUpdate(form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              form.password = this.createSm3Sign(form.password)
              appUserAdd(form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }

        }
      });
    },
    submitPwd() {//密码提交
      this.$refs["form_pwd"].validate(valid => {
        if (valid) {
          let form_pwd = {...this.form_pwd}
          form_pwd.newPassword = this.createSm3Sign(form_pwd.newPassword)
          updatePassWord(form_pwd).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openPwd = false;
            this.getList();
          });
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
 .amap-icon img,.amap-icon,
.amap-marker-content img{
    width: 25px!important;
    height: 34px!important;
}
#container {width:650px; height: 300px; }
/deep/ .tree-border{
    border:1px solid #f2f2f2;
    border-radius: 5px;
  }
#tree{
   /deep/ .el-tree-node__content{
     .el-checkbox{display: none;}

   }
   /deep/.el-tree-node__children{
     .el-checkbox{display: block;}
   }
}
</style>
